<template>
  <a-modal
    :confirmLoading="loading"
    :title="(model&&model.id) ? '编辑知识库': '新增知识库'"
    :visible="visible"
    :width="960"
    @cancel="() => { $emit('cancel') }"
    @ok="handleOK">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item label="id" style="display: none;">
          <a-input v-decorator="['id']" />
        </a-form-item>

        <a-form-item label="类别">
          <a-select
            v-decorator="[
              'typeId',
              {rules: [{ required: true, message: '请选择' }]}
            ]"
            placeholder="请选择"
            @change="selectCategory">
            <a-select-option v-for="item in typeList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="分类">
          <a-select
            v-decorator="[
              'categoryId',
              {rules: [{ required: true, message: '请选择' }]}
            ]"
            placeholder="请选择">
            <a-select-option v-for="item in categoryList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="标题">
          <a-input v-decorator="['title', { rules: [{ required: true, message: '请输入标题' }] }]" />
        </a-form-item>

        <a-form-item label="作者">
          <a-input v-decorator="['author', { rules: [{ required: true, message: '请输入作者' }] }]" />
        </a-form-item>

        <a-form-item label="摘要">
          <a-input v-decorator="['brief', { rules: [{ required: true, message: '请输入摘要' }] }]" />
        </a-form-item>

        <a-form-item label="封面">
          <a-upload
            v-decorator="[
              'cover',
              {
                valuePropName: 'file',
                getValueFromEvent: normFile,
                rules: [{ required: true, message: '请上传封面图片' }]
              },
            ]"
            :action="uploadApi"
            :show-upload-list="false"
            accept="image/png, image/jpeg"
            class="avatar-uploader"
            list-type="picture-card"
            name="file"
            @change="handleChange">
            <img
              v-if="coverFileList && coverFileList[0]"
              :src="coverFileList[0].response.data.src"
              alt="avatar"
              height="150"
              width="150" />
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-icon v-if="bannerLoading" class="loading" type="loading" />
          <div class="tips">建议尺寸: 300*300</div>
        </a-form-item>

        <!-- <a-form-item label="封面">
          <div class="upload-wrapper">
            <div class="img-list" v-if="fileList.length > 0">
              <div class="img-item" v-for="(item, index) in fileList">
                <img v-if="item.type === 4 || item.type ==='image/png'" class="img" :src="item.response.data.src"
                  alt="avatar" width="690" height="280" />
                <div v-else>{{ item.name }}</div>
                <div class="mask">
                  <a-icon class="myicon" type="eye" @click="handlePreview(item)" />
                  <a-icon class="myicon" type="delete" @click="handleDelete(index)" />
                </div>
              </div>
            </div>
            <a-upload name="file" list-type="picture-card"
              accept="image/png, image/jpeg, application/pdf, application/msword, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :show-upload-list="false" :action="uploadApi" @change="handleContentChange" v-decorator="[
                'files',
                {
                  valuePropName: 'files',
                  getValueFromEvent: contentFile,
                  rules: [{ required: false, message: '请上传封面图片' }]
                },
              ]">
              <div class="upload-btn" v-show="!fileList.length || fileList.length < 5">
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  上传
                </div>
              </div>
            </a-upload>
          </div>
          <a-icon class="loading" type="loading" v-if="fileLoading" />
        </a-form-item> -->

        <a-form-item label="描述内容">
          <!-- <a-textarea :rows="3" v-decorator="['content', { rules: [{ required: true, message: '请输入描述内容！' }] }]" /> -->
          <wang-editor
            v-decorator="['content', { rules: [{ required: true, message: '请输入描述内容！' }] }]"
            :catchData="catchData"
            :htmlData="content"
            :uploadApi="uploadApi"></wang-editor>
        </a-form-item>

        <a-form-item label="访问权限">
          <a-select
            v-decorator="[
              'openScope',
              {rules: [{ required: true, message: '请选择' }]}
            ]"
            placeholder="请选择">
            <a-select-option v-for="item in openScopeList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import api from '@/api/banner'
import { knowledgeCategoryList as list, knowledgeTypeList as typeList } from '@/api/knowledge'
import WangEditor from '@/components/Editor/WangEditor.vue'

// 表单字段
const fields = ['title', 'cover', 'files', 'typeId', 'content', 'id', 'author', 'brief', 'categoryId', 'openScope']
const baseApi = process.env.VUE_APP_API_BASE_URL
// import UploadPreview from '@/components/upload-prevew'
export default {
  components: { WangEditor },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
    return {
      form: this.$form.createForm(this),
      fileList: [],
      coverFileList: [],
      categoryList: [],
      typeList: [],
      openScopeList: [{ id: 0, name: '全部' }, { id: 1, name: '购买用户' }, { id: 2, name: '指定用户' }],
      fileLoading: false,
      bannerLoading: false,
      uploadApi: baseApi + api.upload,
      content: ''
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    this.getTypeList()
    // this.getCategory()
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if (this.model) {
        if (this.model.typeId) {
          // 刷新分类信息，2024年10月2日07:41:30
          this.getCategory(this.model.typeId)
        }
        const content = this.model && this.model.files || null
        this.fileList = content && content.map((i, j) => {
          return {
            response: { data: { src: i.fileUrl } },
            status: 'done',
            uid: j,
            type: i.fileType,
            size: i.fileSize,
            name: i.fileName
          }
        }) || []
        this.form.setFieldsValue(pick(this.model, fields))
        this.content = this.model.content

        // 封面图片回显
        this.coverFileList = [{
          response: { data: { src: this.model.cover } },
          uid: '-' + this.model.id,
          name: this.model.id,
          status: 'done'
        }]
      }
    })
  },
  methods: {
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.bannerLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.coverFileList = info.fileList.slice(-1)
        this.bannerLoading = false
      }
    },
    normFile (e) {
      if (e.file.response && e.file.response.data) {
        // this.form.setFieldsValue({ srcSave: e.file.response.data.srcSave })
        return e.file.response.data.src
      }
      return ''
    },
    catchData (content) {
      this.content = content
    },
    async getTypeList () {
      const res = await typeList({ limit: 10000 })
      if (!res.success) return
      this.typeList = res.data.records
    },
    async getCategory (typeId) {
      const res = await list({ typeId: typeId, limit: 10000 })
      if (!res.success) return
      this.categoryList = res.data.records
    },
    selectCategory (val) {
      this.categoryList = undefined
      this.form.resetFields(['categoryId'])
      this.getCategory(val)
    },
    handleContentChange (info) {
      if (info.file.status === 'uploading') {
        this.fileLoading = true
        return
      }
      if (info.file.status === 'done') {
        // console.log(info)
        this.fileList.push(info.file)
        this.fileLoading = false
      }
    },
    contentFile () {
      const fileList = this.fileList
      if (fileList.length > 0) {
        const arr = fileList.map(i => {
          let size = i.size
          if (!new RegExp('MBKB').test(i.size) && /^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(i.size)) {
            const ksize = (i.size / 1024)
            size = ksize < 1024 ? `${(ksize).toFixed(2)}KB` : `${(ksize / 1024).toFixed(2)}MB`
            // console.log(size)
          }
          return {
            fileType: this.handleType(i.type),
            fileUrl: i.response.data.src,
            fileName: i.name,
            fileSize: size
          }
        })
        return arr
      } else {
        return null
      }
    },
    handleType (val) {
      if (/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(val)) return val
      let type = 2
      if (new RegExp('msword').test(val)) {
        type = 1
      } else if (new RegExp('pdf').test(val)) {
        type = 3
      } else if (new RegExp('image').test(val)) {
        type = 4
      }
      return type
    },
    handlePreview (e) {
      window.open(e.response.data.src, '_blank')
    },
    handleDelete (index) {
      // this.fileList.splice(index, 1)
      // const str = this.contentFile()
      // this.form.setFieldsValue({ files: str })
    },
    handleOK () {
      // const str = this.contentFile()
      const content = this.content
      this.form.setFieldsValue({ content: content })
      this.$emit('ok')
    }
  }
}
</script>
<style lang="less" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.upload-wrapper {
  display: flex;
}

.img-list {
  display: flex;

  .img-item {
    position: relative;
    width: 100px;
    height: 100px;
    padding: 4px;
    overflow: hidden;
    box-sizing: border-box;
    margin-right: 10px;
    border-radius: 10px;
    overflow: hidden;

    &:hover .img-list .img-item .mask {
      display: block;
    }

    .img {
      height: 100%;
      width: 100%;
    }
  }

  .upload-btn {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

  }

  .myicon {
    font-size: 20px;
    color: #fff;

    &:hover {
      color: #1890ff;
    }
  }

  .mask {
    display: none;
    position: absolute;
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, .65);
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
}
</style>
